namespace SimpleWebServices.Web.Routing
{
    using System;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;
    using SimpleWebServices.Data;
    using SimpleWebServices.Models;

    public sealed class SubmissionRoute : RouteBase
    {
        public override RouteData GetRouteData(HttpContextBase httpContext)
        {
            RouteData result = null;

            Route route = SubmissionRoute.GetRoute(httpContext);
            if (null != route)
            {
                result = route.GetRouteData(httpContext);
            }

            return result;
        }

        public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
        {
            if (null == requestContext)
            {
                throw new ArgumentNullException("requestContext");
            }

            VirtualPathData result = null;

            Route route = SubmissionRoute.GetRoute(requestContext.HttpContext);
            if (null != route)
            {
                result = route.GetVirtualPath(requestContext, values);
            }

            return result;
        }

        private static Route GetRoute(HttpContextBase httpContext)
        {
            if (null == httpContext)
            {
                throw new ArgumentNullException("httpContext");
            }

            Route result = null;

            if (httpContext.Request.Path.EndsWith("/submission", StringComparison.OrdinalIgnoreCase))
            {
                if (null != httpContext.Request.Tokenized<FormSubmission>())
                {
                    result = SubmissionRoute.New(httpContext.Request.Path.Substring(1));
                }
            }

            return result;
        }

        private static Route New(ResourcePath path)
        {
            return new Route(path, new MvcRouteHandler())
            {
                Defaults = new RouteValueDictionary(new 
                {
                    controller = "Submission",
                    action = "Process"
                }),
                Constraints = new RouteValueDictionary()
            };
        }
    }
}